package Map_Set;

import java.util.Objects;

class Person{
    public String id;

    public Person(String id) {
        this.id=id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Person person = (Person) o;
        return Objects.equals(id, person.id);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}


public class MyHashBucket2< K,V > {

    static class Node<K,V> {
        //静态类
        public K key;
        public V val;
        public Node<K,V> next;

        public Node(K key, V val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node<K,V>[]  array =(Node<K, V>[]) new Node[10];
    public int usedSize;

    //插入，暂时不考虑扩容
    public void put(K key,V val) {
        //此时 key 不能取模数组的长度
        //因此要把 key 转换成一个合法整数，需要调用 hashcode()
        int hash=key.hashCode();
        int index=hash % this.array.length;

        Node<K,V> cur=array[index];
        while (cur!=null) {
            //当 key相同，更新 val值
            if (cur.key.equals(key)) {
                cur.val=val;
            }
            //当 key不相同，遍历到null进行头插
            cur=cur.next;
        }
        Node<K,V> node=new Node<>(key,val);
        node.next=array[index];
        array[index]=node;

        this.usedSize++;

    }

    public V get(K key) {
        int hash=key.hashCode();
        int index=hash % this.array.length;

        Node<K,V> cur=array[index];
        while (cur!=null) {
            if (cur.key.equals(key)) {
                return cur.val;
            }
            cur=cur.next;
        }
        return null;
    }

    public static void main(String[] args) {
        Person person1=new Person("111");
        Person person2=new Person("111");

        MyHashBucket2<Person, String> hashBucket2 = new MyHashBucket2<Person, String>();
        hashBucket2.put(person1,"sj");
        System.out.println(hashBucket2.get(person2));
        //重写了 hashCode()，所以person2.hashcode()的哈希值和person1相同

    }

    public static void main1(String[] args) {
        Person person1=new Person("111");
        Person person2=new Person("111");

        System.out.println(person1.equals(person2));
        System.out.println(person1.hashCode());//当不重写 hashCode()时，person1 和 person2 的哈希值是不同的
        System.out.println(person2.hashCode());
    }
}
